//
//  LKMyAddContinuInvestViewController.m
//  YLHelper
//
//  Created by she1323 on 2018/5/10.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKMyAddContinuInvestViewController.h"
#import "LKMyContinuInvestFillCell.h"
#import "LKWriteContinuInvestCell.h"
#import "LKWorkOrderDetailContractCell.h"
#import "LKContinuInvestOrderListViewController.h"
#import "LKOrderModel.h"
#import "GFDatePicker.h"
@interface LKMyAddContinuInvestViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UIViewControllerTransitioningDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong)LKBaseTableview *tableView;
@property(nonatomic,strong)NSArray *titlesArray;
@property(nonatomic,copy)NSString *contractCode;
@property(nonatomic,copy)NSString *customerName;
@property(nonatomic,copy)NSString *customerCode;
@property(nonatomic,copy)NSString *investmentAmount;
@property(nonatomic,copy)NSString *incomeSum;
@property(nonatomic,copy)NSString *expirationDate;
@property(nonatomic,copy)NSString *repaymentDate;
@property(nonatomic,copy)NSString *Status;
@property(nonatomic,assign)BOOL isInSystem;
@property(nonatomic,copy)NSString *expirationAmount;
@property(nonatomic,strong)NSMutableArray *orderContinueAttach;
@property(nonatomic,strong)NSMutableArray *cellContentArray;
@property(nonatomic,strong)NSMutableArray *attachArray;
@property(nonatomic,assign) BOOL isHandInput;
@property(nonatomic,strong)NSMutableArray *shengMingArray;
@property(nonatomic,assign)BOOL isOrderApplyHand;
@end

@implementation LKMyAddContinuInvestViewController
-(LKBaseTableview *)tableView{
    if (!_tableView) {
        _tableView = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, 12 + NAVIGATION_BAR_HEIGHT, WIDTH, HEIGHT - (NAVIGATION_BAR_HEIGHT + 12)) style:UITableViewStyleGrouped registercellClasss:@[@"LKMyContinuInvestFillCell",@"LKWriteContinuInvestCell",@"LKWorkOrderDetailContractCell"]];
        [self.view addSubview:_tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHandInput = NO;
    self.tableView.estimatedRowHeight = 200;
    // Do any additional setup after loading the view.
}
-(void)setNavgationBackBtn{
    [super setNavgationBackBtn];
    self.navigationItem.title = @"订单续投申请";
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn setTitleColor:blueDefault forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(commitContinueOrderChange:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

/**
 提交变更

 */
-(void)commitContinueOrderChange:(UIButton *)btn{
    self.Status = @"1";
    NSDictionary *param;
    if (self.isOrderApplyHand) {
            param = [NSDictionary dictionaryWithObjectsAndKeys:self.customerName,@"CustomerName",self.contractCode,@"ContractCode",self.investmentAmount,@"InvestmentAmount",self.incomeSum,@"IncomeSum",self.expirationDate,@"ExpirationDate",self.repaymentDate,@"RepaymentDate",self.Status,@"Status",self.expirationAmount,@"ExpirationAmount",@(NO),@"IsInSystem",self.shengMingArray,@"OrderContinueAttach", nil];
    }else{
            param = [NSDictionary dictionaryWithObjectsAndKeys:self.customerCode,@"CustomerCode",self.customerName,@"CustomerName",self.contractCode,@"ContractCode",self.investmentAmount,@"InvestmentAmount",self.incomeSum,@"IncomeSum",self.expirationDate,@"ExpirationDate",self.repaymentDate,@"RepaymentDate",self.Status,@"Status",self.expirationAmount,@"ExpirationAmount",@(self.isInSystem),@"IsInSystem",self.shengMingArray,@"OrderContinueAttach", nil];
    }

    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:commitContineOrderChangeUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [SVProgressHUD showSuccessWithStatus:@"您的续投申请已提交"];
        UIViewController *vc = self.presentingViewController;
        while (vc.presentingViewController) {
            vc = vc.presentingViewController;
        }
        [vc dismissViewControllerAnimated:YES completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"RealoadChangeSuccessNotice" object:nil];
    } failure:^(NSString * _Nullable errorMessage) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {
        return self.titlesArray.count;
    }
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isOrderApplyHand) {
        LKWriteContinuInvestCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKWriteContinuInvestCell"];
        if (indexPath.section == 0) {
            cell.contentLabel.textColor = blueDefault;
            cell.arrowIcon.hidden = NO;
            return cell;
        }
        if (indexPath.section == 1) {
            switch (indexPath.row) {
                case 0:
                {
                    LKMyContinuInvestFillCell *fillCell = [tableView dequeueReusableCellWithIdentifier:@"LKMyContinuInvestFillCell"];
                    fillCell.contentTF.placeholder = @"请输入";
                    fillCell.contentTF.text = self.customerName;
                    fillCell.titleLabel.text = self.titlesArray[indexPath.row];
                    fillCell.contentTF.tag = 10000 + indexPath.row;
                    [fillCell.contentTF addTarget:self action:@selector(changeSectionOneValue:) forControlEvents:UIControlEventEditingChanged];
                    return fillCell;
                    
                }
                    break;
                case 1:
                {
                    LKMyContinuInvestFillCell *fillCell = [tableView dequeueReusableCellWithIdentifier:@"LKMyContinuInvestFillCell"];
                    fillCell.titleLabel.text = self.titlesArray[indexPath.row];
                    fillCell.contentTF.placeholder = @"请输入";
                    fillCell.contentTF.text = self.investmentAmount;
                    fillCell.contentTF.tag = 10000 + indexPath.row;
                    [fillCell.contentTF addTarget:self action:@selector(changeSectionOneValue:) forControlEvents:UIControlEventEditingChanged];
                    return fillCell;
                }
                    break;
                case 2:
                {
                    LKMyContinuInvestFillCell *fillCell = [tableView dequeueReusableCellWithIdentifier:@"LKMyContinuInvestFillCell"];
                    fillCell.contentTF.placeholder = @"请输入";
                    fillCell.contentTF.text = self.expirationAmount;
                    fillCell.titleLabel.text = self.titlesArray[indexPath.row];
                    fillCell.contentTF.tag = 10000 + indexPath.row;
                    [fillCell.contentTF addTarget:self action:@selector(changeSectionOneValue:) forControlEvents:UIControlEventEditingChanged];
                    return fillCell;
                }
                    break;
                case 3:
                {
                    cell.contentLabel.text = self.expirationDate;
                     cell.titleLabel.text = self.titlesArray[indexPath.row];
                }
                    break;
                case 4:
                {
                    LKMyContinuInvestFillCell *fillCell = [tableView dequeueReusableCellWithIdentifier:@"LKMyContinuInvestFillCell"];
                    fillCell.contentTF.placeholder = @"请输入";
                    fillCell.contentTF.text = self.incomeSum;
                    fillCell.titleLabel.text = self.titlesArray[indexPath.row];
                    fillCell.contentTF.tag = 10000 + indexPath.row;
                    [fillCell.contentTF addTarget:self action:@selector(changeSectionOneValue:) forControlEvents:UIControlEventEditingChanged];
                    return fillCell;
                }
                    break;
                case 5:
                {
                    cell.contentLabel.text = self.repaymentDate;
                    cell.titleLabel.text = self.titlesArray[indexPath.row];
                }
                    break;
                default:
                    break;
            }

//            if (self.isHandInput) {
//                LKMyContinuInvestFillCell *fillCell = [tableView dequeueReusableCellWithIdentifier:@"LKMyContinuInvestFillCell"];
//                fillCell.titleLabel.text = self.titlesArray[indexPath.row];
//                cell.contentTF.tag = 10000 + indexPath.row;
//                [cell.contentTF addTarget:self action:@selector(changeSectionOneValue:) forControlEvents:UIControlEventEditingChanged];
//                return fillCell;
//            }
//            cell.titleLabel.text = self.titlesArray[indexPath.row];
//            if (self.cellContentArray.count > 0) {
//                cell.contentLabel.text = self.cellContentArray[indexPath.row];
//            }else{
//                cell.contentLabel.text  = @"";
//            }
//
//            cell.arrowIcon.hidden = YES;
//            return cell;
        }
        if (indexPath.section == 2) {
            LKWorkOrderDetailContractCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKWorkOrderDetailContractCell"];
            cell.arrorBtn.hidden = YES;
            cell.titleLabel.text = @"上传续约声明";
            cell.iconImageView.image = [UIImage imageNamed:@"shangchuan"];
            cell.iconImageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoPickPiture:)];
            [cell.iconImageView addGestureRecognizer:tap];
            return cell;
        }
        return cell;
        
    }
    LKWriteContinuInvestCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKWriteContinuInvestCell"];
    if (indexPath.section == 0) {
        cell.contentLabel.textColor = blueDefault;
        cell.arrowIcon.hidden = NO;
        return cell;
    }
    if (indexPath.section == 1) {
        if (self.isHandInput) {
            LKMyContinuInvestFillCell *fillCell = [tableView dequeueReusableCellWithIdentifier:@"LKMyContinuInvestFillCell"];
            fillCell.titleLabel.text = self.titlesArray[indexPath.row];
            cell.contentTF.tag = 10000 + indexPath.row;
            [cell.contentTF addTarget:self action:@selector(changeSectionOneValue:) forControlEvents:UIControlEventEditingChanged];
            return fillCell;
        }
        cell.titleLabel.text = self.titlesArray[indexPath.row];
        if (self.cellContentArray.count > 0) {
           cell.contentLabel.text = self.cellContentArray[indexPath.row];
        }else{
            cell.contentLabel.text  = @"";
        }
        
        cell.arrowIcon.hidden = YES;
        return cell;
    }
    if (indexPath.section == 2) {
        LKWorkOrderDetailContractCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKWorkOrderDetailContractCell"];
        cell.arrorBtn.hidden = YES;
        cell.titleLabel.text = @"上传续约声明";
        cell.iconImageView.image = [UIImage imageNamed:@"shangchuan"];
        cell.iconImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoPickPiture:)];
        [cell.iconImageView addGestureRecognizer:tap];
        return cell;
    }
    return cell;
}
/**
 textfield的文本框的输入变化
 
 */
-(void)changeSectionOneValue:(UITextField *)textFiled{
    switch (textFiled.tag) {
        case 10000:
        {
            self.customerName = textFiled.text;
            
        }
            break;
        case 10001:
        {
            self.investmentAmount = textFiled.text;
            
        }
            break;
        case 10002:
        {
            self.expirationAmount = textFiled.text;
            
        }
            break;
        case 10003:
        {
//            self.expirationDate = textFiled.text;
            
        }
            break;
        case 10004:
        {
            self.incomeSum = textFiled.text;
            
        }
            break;
        case 10005:
        {
            self.repaymentDate = textFiled.text;
            
        }
            break;
        default:
            break;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 2 ? 180 : 43;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0000000000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 12;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = cellHeaderBgColor;
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf)
    if (self.isOrderApplyHand) {
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        if (indexPath.section == 1) {
            
            switch (indexPath.row) {
                case 3:
                    {
                        [GFDatePicker showCustomDatePickerAtView:[UIApplication sharedApplication].keyWindow choosedDateBlock:^(NSDate *date) {
                            NSString *dateStr = [NSString stringWithFormat:@"%@",date];
                            NSString *timeStr = [dateStr componentsSeparatedByString:@" "][0];
                            LKWriteContinuInvestCell *cell = (LKWriteContinuInvestCell *)[tableView cellForRowAtIndexPath:indexPath];
                            cell.contentLabel.text = timeStr;
                            weakSelf.expirationDate = timeStr;
                        } cancelBlock:^{
                            
                        }];
                    }
                    break;
                case 5:
                {
                    [GFDatePicker showCustomDatePickerAtView:[UIApplication sharedApplication].keyWindow choosedDateBlock:^(NSDate *date) {
                        NSString *dateStr = [NSString stringWithFormat:@"%@",date];
                        NSString *timeStr = [dateStr componentsSeparatedByString:@" "][0];
                        LKWriteContinuInvestCell *cell = (LKWriteContinuInvestCell *)[tableView cellForRowAtIndexPath:indexPath];
                        cell.contentLabel.text = timeStr;
                        weakSelf.repaymentDate = timeStr;
                    } cancelBlock:^{
                        
                    }];
                }
                    break;
                default:
                    break;
            }
        }
    }
    if (indexPath.section == 0) {
        LKContinuInvestOrderListViewController *vc = [[LKContinuInvestOrderListViewController alloc] init];
        vc.handInputOrderApply = YES;
        vc.contractCodeBlock = ^(LKOrderModel *orderModel) {
            LKWriteContinuInvestCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.contentLabel.text = orderModel.contractCode;
            weakSelf.contractCode = orderModel.contractCode;
            if (orderModel.customerName) {
                [weakSelf judgeGetIsExit];
            }else{
                [weakSelf.tableView reloadSection:1 withRowAnimation:UITableViewRowAnimationNone];
            }

        };
        vc.orderApplyHandBlock = ^(NSString *contractCode, BOOL isHandInput) {
            LKWriteContinuInvestCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.contentLabel.text = contractCode;
            weakSelf.contractCode = contractCode;
            weakSelf.isOrderApplyHand = isHandInput;
            [weakSelf.tableView reloadSection:1 withRowAnimation:UITableViewRowAnimationNone];
        };
        
        
        
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(NSArray *)titlesArray{
    if (!_titlesArray) {
        _titlesArray = @[@"出借人",@"合同金额",@"到期金额",@"到期日期",@"应支付利息",@"还款日期"];
    }
    return _titlesArray;
}

/**
 判断续投订单是否在系统中
 */
-(void)judgeGetIsExit{
    [self.cellContentArray removeAllObjects];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:self.contractCode,@"ContractCode",@(YES),@"IsContinuedInvestment", nil];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:judeIsInSystemUrl header:[LKUserInforTool header] parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        LKOrderModel *orderModle = [LKOrderModel modelWithDictionary:responseObject[@"result"]];
        self.customerCode = orderModle.customerCode;
        self.customerName = orderModle.customerName;
        self.incomeSum = orderModle.incomeSum;
        self.expirationAmount = orderModle.expirationAmount;
        self.expirationDate = responseObject[@"result"][@"expirationDateTest"];
        self.investmentAmount = orderModle.investmentAmount;
        self.repaymentDate = orderModle.repaymentDateTest;
        self.isInSystem = [responseObject[@"result"][@"isInSystem"] boolValue];
        self.Status = responseObject[@"result"][@"statusTest"];

        [self.cellContentArray addObjectsFromArray:@[self.customerName,self.investmentAmount,self.expirationAmount,self.expirationDate,self.incomeSum,self.repaymentDate]];
        [self.tableView reloadSection:1 withRowAnimation:UITableViewRowAnimationNone];
//        if ([responseObject[@"result"][@"isInSystem"] integerValue]) {
//            [SVProgressHUD showInfoWithStatus:@"订单已存在系统中"];
//        }else{
//
//        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
-(NSMutableArray *)orderContinueAttach{
    if (!_orderContinueAttach) {
        _orderContinueAttach = [[NSMutableArray alloc] init];
    }
    return _orderContinueAttach;
}
-(NSMutableArray *)cellContentArray{
    if (!_cellContentArray) {
        _cellContentArray = [[NSMutableArray alloc] init];
    }
    return _cellContentArray;
}
-(NSMutableArray *)attachArray{
    if (!_attachArray) {
        _attachArray = [[NSMutableArray alloc] init];
    }
    return _attachArray;
}
-(void)gotoPickPiture:(UITapGestureRecognizer *)tap{
     [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    UIView *view = tap.view;
    //             判断是否支持相机
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            [SVProgressHUD showInfoWithStatus:@"无法使用相机"];
            return;
        }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self camerOrAlbumsPhotoChooseWithAlert:alert AndSourceType:sourceType];
    [self presentViewController:alert animated:YES completion:nil];
}
/**
 从相册或者相机中选择图片
 
 @param alert 弹框
 @param sourceTypea 相机或者相册
 */
-(void)camerOrAlbumsPhotoChooseWithAlert:(UIAlertController *)alert AndSourceType:(NSInteger) sourceTypea{
    __block NSInteger sourceType = sourceTypea;
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //来源:相机
        sourceType = UIImagePickerControllerSourceTypeCamera;
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = (id)self;
        imagePickerController.allowsEditing = NO;
        imagePickerController.sourceType = sourceType;
        imagePickerController.transitioningDelegate = self;
        imagePickerController.modalPresentationStyle = UIModalPresentationCustom;
        [self presentViewController:imagePickerController animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //来源:相册
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = (id)self;
        imagePickerController.allowsEditing = NO;
        imagePickerController.navigationBar.translucent = NO;
        [imagePickerController.navigationBar setBarTintColor:blueDefault];
        imagePickerController.sourceType = sourceType;
        imagePickerController.transitioningDelegate = self;
        imagePickerController.modalPresentationStyle = UIModalPresentationCustom;
        [self presentViewController:imagePickerController animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
}
#pragma mark - 调用相机的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    LKWorkOrderDetailContractCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
    UIImage *aimage = image;
    cell.iconImageView.image = aimage;
    [self.shengMingArray removeAllObjects];
    [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:otherOfPictureUrl parameters:nil imageArray:@[aimage] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:responseObject[@"fileName"],@"ContinueAttachName",responseObject[@"suffix"],@"ContinueSuffix",responseObject[@"fileUrl"],@"ContinueAttachUrl",responseObject[@"streamLength"],@"ContinueAttachSize", nil];
        [self.shengMingArray addObject:dic];
    } failure:^(NSString * _Nullable error) {
        
    }];
}
//缩放图片到指定大小的imageview
- (UIImage*)imageCompressWithSimple:(UIImage*)image scaledToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0,0,size.width,size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
-(NSMutableArray *)shengMingArray{
    if (!_shengMingArray) {
        _shengMingArray = [[NSMutableArray alloc] init];
    }
    return _shengMingArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
